<?php

  function queryCatalogCSW($query) {
    $xml = simplexml_load_string(
      file_get_contents(
         'http://testbedapps.sura.org/gi-cat/services/cswiso'
        ,false
        ,stream_context_create(array('http' => array(
           'method'  => 'POST'
          ,'header'  => 'Content-type: text/xml'
          ,'content' => $query
        )))
      )
    );

    $cswNs = 'http://www.opengis.net/cat/csw/2.0.2';
    $gmdNs = 'http://www.isotc211.org/2005/gmd';
    $gcoNs = 'http://www.isotc211.org/2005/gco';
    $gmiNs = 'http://www.isotc211.org/2005/gmi';
    $srvNs = 'http://www.isotc211.org/2005/srv';

    $d = array();
    foreach ($xml->children($cswNs)->{'SearchResults'} as $searchResults) {
      foreach ($searchResults->children($gmdNs)->{'MD_Metadata'} as $mdMetadata) {
        $m = array(
           'title' => ''
          ,'type'  => ''
          ,'svc'   => array()
        );
        foreach ($mdMetadata->children($gmdNs)->{'identificationInfo'} as $identificationInfo) {
          foreach ($identificationInfo->children($gmdNs)->{'MD_DataIdentification'} as $dataIdentification) {
            $m['title'] = sprintf("%s",$dataIdentification->children($gmdNs)->{'citation'}[0]->children($gmdNs)->{'CI_Citation'}[0]->children($gmdNs)->{'title'}[0]->children($gcoNs)->{'CharacterString'});
          }
          foreach ($identificationInfo->children($srvNs)->{'SV_ServiceIdentification'} as $serviceIdentification) {
            array_push($m['svc'],sprintf("%s",$serviceIdentification->attributes()->{'id'}));
          }
        }
        foreach ($mdMetadata->children($gmdNs)->{'contentInfo'} as $contentInfo) {
          foreach ($contentInfo->children($gmiNs)->{'MI_CoverageDescription'} as $coverageDescription) {
            foreach ($coverageDescription->children($gmdNs)->{'contentType'} as $contentType) {
              $type = sprintf("%s",$contentType->children($gmdNs)->{'MD_CoverageContentTypeCode'});
              if ($type != '') {
                $m['type'] = $type == 'modelResult' ? 'model' : ($type == 'physicalMeasurement' ? 'obs' : '');
              }
            }
          }
        }
        array_push($d,$m);
      }
    }
    
    return $d;
  }

  function queryCatalogOpenSearch($query) {
    $xml = simplexml_load_file("http://testbedapps.sura.org/gi-cat/services/opensearch?si=0&ct=1000&st=$query&bbox=&rel=overlaps&loc=&ts=&te=&outputFormat=text/html");
    $d = array();
    foreach ($xml->{'entry'} as $entry) {
      array_push($d,array(
        'title' => sprintf("%s",$entry->{'title'})
      ));
    }

    return $d;
  }

?>
